<template>
  <CrudTable
    mode="tree"
    :buttons="tableButtons"
    row-selection-type="multiple"
    :columns="tableColumns"
    @currentChange="handleSelectChange"
    :tableData="pageData.tableData"
    :loading="pageData.loading"
    @rowDbClick="handleRowDbClick"
    :showRefresh="false"
    :showExport="false"
  >
    <template #rowOperations="{ row }">
      <div class="crud-table__row_operations">
        <t-link variant="text" theme="primary" @click="handleOperateRow('view', row)">查看</t-link>
        <t-link variant="text" theme="primary" @click="handleOperateRow('edit', row)">修改</t-link>
        <t-link variant="text" theme="danger" @click="handleOperateRow('delete', row)">删除</t-link>
      </div>
    </template>
  </CrudTable>

  <EditForm
    v-if="pageData.showEditForm"
    :dialogVisible="pageData.showEditForm"
    :mode="pageData.editFormMode"
    :id="pageData.selectedRowId"
    @close="handleDialogClose"
  />
</template>

<script lang="tsx" setup>
import { ref, computed, reactive, defineAsyncComponent } from "vue";
import { DialogPlugin, MessagePlugin, type TableProps } from "tdesign-vue-next";

import { http } from "@/utils/fetch";
import { getValueBySelectData } from "@/utils/tools";
import { useMenuStore } from "@/stores/modules/menu";

import { STATUS_DATA } from "@/common/constants";

const EditForm = defineAsyncComponent(() => import("./components/EditForm.vue"));

const GET_LIST_PATH = "/menu/findAll"; // 查询信息接口
const DELETE_ITEM_PATH = "/menu/delete"; // 删除接口

const menuStore = useMenuStore();

const pageData = reactive<Record<string, any>>({
  loading: false,
  tableData: [],
  selectedRow: {},
  selectedRowId: "",
  showEditForm: false,
  editFormMode: ""
});

// 表格操作按钮配置
const tableButtons = computed(() => [
  {
    name: "新增",
    click: () => {
      handleOperateRow("new");
    }
  },
  {
    name: "刷新侧边栏菜单",
    click: () => {
      refreshMyMenu();
    }
  }
]);

// 表格列配置
const tableColumns = ref<TableProps["columns"]>([
  {
    colKey: "name",
    title: "菜单名称",
    width: 250
  },
  {
    colKey: "code",
    title: "菜单代号",
    width: 200
  },
  {
    colKey: "sort",
    title: "优先级",
    width: 130
  },
  {
    colKey: "status",
    title: "状态",
    cell: (h, { row }) => {
      return getValueBySelectData(STATUS_DATA, row.status);
    },
    width: 200
  }
]);

// 获取列表数据
const findAllList = async () => {
  pageData.loading = true;
  const resultData = await http("GET", GET_LIST_PATH);
  if (resultData.code === 200) {
    if (resultData.data) {
      pageData.tableData = resultData.data;
    }
    pageData.loading = false;
  }
};

// 对话框关闭时的处理函数
const handleDialogClose = (e: string) => {
  if (e === "success") {
    MessagePlugin.success("操作成功！");
    findAllList();
    refreshMyMenu();
  }
  pageData.showEditForm = false;
};

const refreshMyMenu = async () => {
  const resultData = await http("GET", "/menu/findUserMenu");
  if (resultData.code === 200) {
    menuStore.setMenuData(resultData.data);
    MessagePlugin.success("刷新成功！");
  }
};
const handleRowDbClick = (context: Record<string, any>) => {
  handleOperateRow("view", context.row);
};

const handleOperateRow = (mode: string, row?: Record<string, any>) => {
  if (mode !== "delete") {
    if (mode === "new") {
      pageData.selectedRow = {};
      pageData.selectedRowId = "";
    } else {
      pageData.selectedRow = row!;
      pageData.selectedRowId = row!.id;
    }
    pageData.editFormMode = mode;
    pageData.showEditForm = true;
  } else if (mode === "delete") {
    const confirmDialog = DialogPlugin({
      header: "警告",
      body: "确定要删除这一条数据吗？",
      confirmBtn: "确定",
      cancelBtn: "取消",
      theme: "warning",

      onConfirm: async () => {
        const deleteData = await http("DELETE", `${DELETE_ITEM_PATH}?id=${row!.id}`);
        if (deleteData.code === 200) {
          MessagePlugin.success("删除成功！");
          findAllList();
          confirmDialog.hide();
        }
      },
      onClose: () => {
        confirmDialog.hide();
      }
    });
  } else {
    MessagePlugin.error("错误：未知的表格操作模式。");
  }
};

const handleSelectChange = (e: Record<string, any>) => {
  pageData.selectedRowsEvent = e;
};

// 初始化列表
findAllList();
</script>
